package com.df.gamesynctest.msg;

import com.alibaba.fastjson2.JSON;
import com.df.gamesynctest.net.MsgManager;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


public class MsgWrapper {

    public int playerId;
    public int id;
    public Object msg;
    private ByteBuf msgByteBuf;

    public static MsgWrapper createMsgWrapper(Object msg){
        //TODO 消息id和类型应该提前收集
        Integer id = MsgManager.getInstance().msgType2id.get(msg.getClass());
        if(id==null){
            System.out.println("未根据消息类型找到id："+msg.getClass().getSimpleName());
            return null;
        }
        MsgWrapper wrapper = new MsgWrapper();
        wrapper.id = id;
        wrapper.msg = msg;
        return wrapper;
    }

    public ByteBuf toByteBuff(){
        //返回的bytebuf不缓存，因为广播时，各个channel时不同的线程，可能会出现线程安全问题
        String jsonString = JSON.toJSONString(msg);
        byte[] dataBytes = jsonString.getBytes(StandardCharsets.UTF_8);
        //4（长度）+4(消息id)+n(数据长度)
        int len =  8 + dataBytes.length;
        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.heapBuffer(len);
        byteBuf.writeInt(len);
        byteBuf.writeInt(id);
        byteBuf.writeBytes(dataBytes);
        return byteBuf;

    }
}
